package com.alks.function.controller.task;

import com.alks.common.aop.RedisLock;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.procurement.OrderUsageDiffDto;
import com.alks.function.mapper.procurement.OrderUsageDiffMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 采购单耗与当前bom差异
 */
@Component
@Slf4j
@EnableScheduling
@EnableAsync
public class OrderUsageDiffTask {

    @Autowired
    private OrderUsageDiffMapper orderUsageDiffMapper;

    /**
     * 获取采购单耗与当前bom差异
     * @throws ServiceErrorException
     */
    @Async("TaskExecutor")
    @Transactional
    //@Scheduled(cron = "0 0 5,13,18 * * ?") //每天的5点，13点，18点
    //@Scheduled(initialDelay = 5000, fixedRate = 86400000) // 5秒后首次执行，之后每天执行一
    @RedisLock(key = "task:OrderUsageDiffTask.ScheduleGetOrderUsageDiff")
    public void ScheduleGetOrderUsageDiff() throws ServiceErrorException {
        log.info("定时任务执行开始, 获取采购单耗与当前bom差异 开始：");
        //1.先删除差异表中所有数据
        orderUsageDiffMapper.deleteOrderUsageDiff();

        //2.查询当前采购单耗差异
        List<OrderUsageDiffDto> list = orderUsageDiffMapper.getOrderUsageDiff();

        //3.把有差异的材料写入到新表
        if (ObjectUtils.isNotEmpty(list)) {
            orderUsageDiffMapper.addOrderUsageDiff(list);
            log.info("定时任务执行成功, 获取采购单耗与当前bom差异 结束");
        }else{
            log.info("定时任务执行中没有发现采购单耗与当前bom差异的材料>>>NOT_FOUND");
        }
    }

}
